/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.group.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jeeplus.modules.group.mapper.GroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.group.entity.Group;
import com.jeeplus.modules.groupbill.entity.GroupBill;
import com.jeeplus.modules.groupbill.mapper.GroupBillMapper;

/**
 * 实体商家Service
 * @author lixinapp
 * @version 2019-10-16
 */
@Service
@Transactional(readOnly = true)
public class GroupService extends CrudService<GroupMapper, Group> {
	@Autowired
	private GroupBillMapper groupBillMapper;


	public Group get(String id) {
		return super.get(id);
	}
	public Object executeGetSql(String sql){
		return mapper.executeGetSql(sql);
	}
	public List<Group> findList(Group group) {
		return super.findList(group);
	}
	
	public Page<Group> findPage(Page<Group> page, Group group) {
		return super.findPage(page, group);
	}
	
	@Transactional(readOnly = false)
	public void save(Group group) {
		super.save(group);
	}
	
	@Transactional(readOnly = false)
	public void delete(Group group) {
		super.delete(group);
	}

	@Transactional(readOnly = false)
	public void pay(Group group) {
		super.save(group);
		// 其他逻辑处理
		
	}

	/**
	 * 改余额
	 * @param group 商家
	 * @param title 标题
	 * @param amount 金额
	 * @param type 0支出 1收入
	 * @param orderId 订单号
	 * @param content 描述
	 * @param username 收货人
	 * @param phone 电话
	 */
	@Transactional(readOnly = false)
	public synchronized void updateBalance(Group group, String title, String amount, String type, String orderId, String content, String username, String phone, Date finishDate) {
		// 添加账单记录
		GroupBill groupBill = new GroupBill();
		groupBill.preInsert();
		groupBill.setGroup(group);
		groupBill.setTitle(title);
		groupBill.setAmount(amount);
		groupBill.setType(type);
		groupBill.setOrderId(orderId);
		groupBill.setContent(content);
		groupBill.setQty(1);
		groupBill.setUsername(username);
		groupBill.setPhone(phone);
		groupBill.setFinishDate(finishDate);
		groupBillMapper.insert(groupBill);
		
		// 修改余额
		if ("0".equals(type)) {
			mapper.execUpdateSql("UPDATE t_group SET balance = balance - "+amount+" WHERE id = '"+group.getId()+"'");
		} else {
			mapper.execUpdateSql("UPDATE t_group SET balance = balance + "+amount+" WHERE id = '"+group.getId()+"'");
		}
	}

	public List<Map<String, Object>> groupOption(String groupId, String beginDate, String endDate) {
		return mapper.groupOption(groupId, beginDate, endDate);
	}
	
}